# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4

##
## Copyright (C) 2009 - George Y. Kussumoto <georgeyk.dev@gmail.com>
##
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public License
## as published by the Free Software Foundation; either version 2
## of the License, or (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., or visit: http://www.gnu.org/.
##
##
""" Twitter API/TwitHeroApp Layer functions """


import google.appengine.ext.db as db

from twitheroapp.models.battle import Battle
from twitheroapp.models.hero import Hero, HeroClass
from twitheroapp.models.stat import classify_tweets
from twitheroapp.twitter import twitter

#
# Globals
#

# This is probably the wrong way to handle this.
MAX_API_CALLS = 100
API_CALLS = 0
API = twitter.Api()


#
# Functions
#

def get_tweets(username, number=13):
    global API_CALLS
    API_CALLS += 1

    for tweet in API.GetUserTimeline(username, count=number):
        yield tweet


def get_hero_class(username):
    tweets = get_tweets(username)
    classification = classify_tweets(tweets)[0]
    query = db.Query(HeroClass)

    if classification == 'rts':
        name = u'Retweeter'
    elif classification == 'pics':
        name = u'Picturer'
    elif classification == 'links':
        name = u'Linker'
    elif classification == 'answers':
        name = u'Answerer'
    else:
        name = u'Trender'

    query.filter('name =', name)
    heroclass = query.get()
    assert heroclass is not None

    return heroclass


def create_hero(username):
    heroclass = get_hero_class(username)
    hero = Hero(name=username, heroclass=heroclass.key())
    hero.put()
    return hero


def update_hero_values(hero):
    heroclass = get_hero_class(hero.name)
    if heroclass.name != hero.heroclass.name:
        hero.heroclass = heroclass.key()
